package com.lst.projectlib.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;

import com.lst.projectlib.R;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/2/15.
 */

public class PermissionUtils {
    private static final String TAG = PermissionUtils.class.getSimpleName();
    public static final int CODE_MULTI_PERMISSION = 100;

    public static final int CODE_RECORD_AUDIO = 0;
    public static final int CODE_READ_CONTACTS = 1;
    public static final int CODE_READ_PHONE_STATE = 2;
    public static final int CODE_READ_CALENDAR = 3;
    public static final int CODE_CAMERA = 4;
    public static final int CODE_ACCESS_FINE_LOCATION = 5;
    public static final int CODE_BODY_SENSORS = 6;
    public static final int CODE_READ_EXTERNAL_STORAGE = 7;
    public static final int CODE_READ_SMS = 8;

    public static final String PERMISSION_RECORD_AUDIO = Manifest.permission.RECORD_AUDIO;//话筒听筒组
    public static final String PERMISSION_READ_CONTACTS = Manifest.permission.READ_CONTACTS;//联系人组
    public static final String PERMISSION_READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;//电话状态组
    public static final String PERMISSION_READ_CALENDAR = Manifest.permission.READ_CALENDAR;//日历组
    public static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;//相机组
    public static final String PERMISSION_ACCESS_FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;//定位组
    public static final String PERMISSION_BODY_SENSORS = Manifest.permission.BODY_SENSORS;//传感器组
    public static final String PERMISSION_READ_EXTERNAL_STORAGE = Manifest.permission.READ_EXTERNAL_STORAGE;//读写本地数据组
    public static final String PERMISSION_READ_SMS = Manifest.permission.READ_SMS;//读写手机短信组

    private static final String[] requestPermissions = {
            PERMISSION_RECORD_AUDIO,
            PERMISSION_READ_CONTACTS,
            PERMISSION_READ_PHONE_STATE,
            PERMISSION_READ_CALENDAR,
            PERMISSION_CAMERA,
            PERMISSION_ACCESS_FINE_LOCATION,
            PERMISSION_BODY_SENSORS,
            PERMISSION_READ_EXTERNAL_STORAGE,
            PERMISSION_READ_SMS,
    };

    public interface PermissionGrant {
        void onPermissionGranted(int requestCode, String msg);
        void onPermissionDeny(int requestCode, String msg);
    }

    /**
     * only check permission
     * @param activity
     * @param requestCode
     * @return
     */
    public static boolean checkPermission(final Activity activity, final int requestCode) {
        if (activity == null) {
            return false;
        }

        Log.i(TAG, "requestPermission requestCode:" + requestCode);
        if (requestCode < 0 || requestCode >= requestPermissions.length) {
            Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);
            return false;
        }

        final String requestPermission = requestPermissions[requestCode];

        //如果是6.0以下的手机，ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED，
        // 但是，如果用户关闭了你申请的权限，ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null)，
        // 你可以使用try{}catch(){},处理异常，也可以在这个地方，低于23就什么都不做，
        // 个人建议try{}catch(){}单独处理，提示用户开启权限。
//        if (Build.VERSION.SDK_INT < 23) {
//            return;
//        }

        int checkSelfPermission;
        try {
            checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
        } catch (RuntimeException e) {
            Toast.makeText(activity, "please open this permission", Toast.LENGTH_SHORT)
                    .show();
            Log.e(TAG, "RuntimeException:" + e.getMessage());
            return false;
        }

        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED");

            Log.d(TAG, "ActivityCompat.requestPermissions");
            return false;
        } else {
            Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED");
            return true;
        }
    }

    /**
     * Requests permission.
     *
     * @param activity
     * @param requestCode request code, e.g. if you need request CAMERA permission,parameters is PermissionUtils.CODE_CAMERA
     */
    public static void requestPermission(final Activity activity, final int requestCode, PermissionGrant permissionGrant) {
        if (activity == null) {
            return;
        }

        Log.i(TAG, "requestPermission requestCode:" + requestCode);
        if (requestCode < 0 || requestCode >= requestPermissions.length) {
            Log.w(TAG, "requestPermission illegal requestCode:" + requestCode);
            return;
        }

        final String requestPermission = requestPermissions[requestCode];

        //如果是6.0以下的手机，ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED，
        // 但是，如果用户关闭了你申请的权限，ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null)，
        // 你可以使用try{}catch(){},处理异常，也可以在这个地方，低于23就什么都不做，
        // 个人建议try{}catch(){}单独处理，提示用户开启权限。
//        if (Build.VERSION.SDK_INT < 23) {
//            return;
//        }

        int checkSelfPermission;
        try {
            checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
        } catch (RuntimeException e) {
            Toast.makeText(activity, "please open this permission", Toast.LENGTH_SHORT)
                    .show();
            Log.e(TAG, "RuntimeException:" + e.getMessage());
            return;
        }

        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED");

            Log.d(TAG, "ActivityCompat.requestPermissions");
            ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
        } else {
            Log.d(TAG, "ActivityCompat.checkSelfPermission ==== PackageManager.PERMISSION_GRANTED");
            if(permissionGrant!=null){
                permissionGrant.onPermissionGranted(requestCode,"opened:" + requestPermissions[requestCode]);
            }
        }
    }

    private static void requestMultiResult(final Activity activity, int requestCode, String[] permissions, int[] grantResults, final PermissionGrant permissionGrant) {
        if (activity == null) {
            return;
        }
        //TODO
        Log.d(TAG, "onRequestPermissionsResult permissions length:" + permissions.length);

        ArrayList<String> notGranted = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            Log.d(TAG, "permissions: [i]:" + i + ", permissions[i]" + permissions[i] + ",grantResults[i]:" + grantResults[i]);
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                notGranted.add(permissions[i]);
            }
        }

        if (notGranted.size() == 0) {
            Log.d(TAG, "all permission success" + notGranted);
            if (permissionGrant!=null){
                permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION, "all permission success" + notGranted);
            }
        } else {
            final List<String> shouldRationalePermissionsList = getNoGrantedPermissionShowRationale(activity, permissions);
            if(shouldRationalePermissionsList != null && shouldRationalePermissionsList.size() > 0){
                Log.d(TAG, "showMessageOKCancel requestPermissions");

                String permissionsMulti = activity.getResources().getString(R.string.permission_multi_hint);
                showMessageOKCancel(activity, permissionsMulti,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                ActivityCompat.requestPermissions(activity, shouldRationalePermissionsList.toArray(new String[shouldRationalePermissionsList.size()]),
                                        CODE_MULTI_PERMISSION);
                                Log.d(TAG, "showMessageOKCancel requestPermissions");
                            }
                        }, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (permissionGrant != null){
                                    permissionGrant.onPermissionDeny(CODE_MULTI_PERMISSION, "permission all deny");
                                }
                            }
                        });
            }else{
                String permissionsMulti = activity.getResources().getString(R.string.permission_multi_hint);
                String permissionsSetPath = activity.getResources().getString(R.string.permission_set_path_hint);

                openSettingActivity(activity, requestCode, "permission multi", permissionGrant, permissionsMulti + "\n" + permissionsSetPath);
            }
        }
    }

    /**
     * 一次申请多个权限
     */
    public static void requestMultiPermissions(final Activity activity, int[] requestCodeList, PermissionGrant permissionGrant) {
        if (activity == null) {
            return;
        }

        //如果是6.0以下的手机，ActivityCompat.checkSelfPermission()会始终等于PERMISSION_GRANTED，
        // 但是，如果用户关闭了你申请的权限，ActivityCompat.checkSelfPermission(),会导致程序崩溃(java.lang.RuntimeException: Unknown exception code: 1 msg null)，
        // 你可以使用try{}catch(){},处理异常，也可以在这个地方，低于23就什么都不做，
        // 个人建议try{}catch(){}单独处理，提示用户开启权限。
//        if (Build.VERSION.SDK_INT < 23) {
//            return;
//        }

        List<String> permissionsList = getNoGrantedPermission(activity, requestCodeList);

        //TODO checkSelfPermission
        if (permissionsList != null && permissionsList.size() > 0) {
            ActivityCompat.requestPermissions(activity, permissionsList.toArray(new String[permissionsList.size()]), CODE_MULTI_PERMISSION);
            Log.d(TAG, "showMessageOKCancel requestPermissions");
        } else {
            if (permissionGrant != null){
                permissionGrant.onPermissionGranted(CODE_MULTI_PERMISSION, "permission all allow");
            }
        }

    }

    private static void shouldShowRationale(final Activity activity, final int requestCode, final String requestPermission, final PermissionGrant permissionGrant) {
        //TODO
        String[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);
        showMessageOKCancel(activity, permissionsHint[requestCode], new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                ActivityCompat.requestPermissions(activity, new String[]{requestPermission}, requestCode);
                Log.d(TAG, "showMessage OK requestPermissions:" + requestPermission);
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "showMessage cancel requestPermissions:" + requestPermission);
                if(permissionGrant!=null){
                    permissionGrant.onPermissionDeny(requestCode,"opened:" + requestPermissions[requestCode]);
                }
            }
        });
    }

    private static void showMessageOKCancel(final Activity context, String message, DialogInterface.OnClickListener okListener, DialogInterface.OnClickListener cancelListener) {
        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setMessage(message)
                .setPositiveButton("去设置", okListener)
                .setNegativeButton("暂不", cancelListener)
                .create()
                .show();

    }

    /**
     * @param activity
     * @param requestCode  Need consistent with requestPermission
     * @param permissions
     * @param grantResults
     */
    public static void requestPermissionsResult(final Activity activity, final int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults, PermissionGrant permissionGrant) {
        if (activity == null) {
            return;
        }
        Log.d(TAG, "requestPermissionsResult requestCode:" + requestCode);

        if (requestCode == CODE_MULTI_PERMISSION) {
            requestMultiResult(activity, requestCode, permissions, grantResults, permissionGrant);
            return;
        }

        if (requestCode < 0 || requestCode >= requestPermissions.length) {
            Log.w(TAG, "requestPermissionsResult illegal requestCode:" + requestCode);
            Toast.makeText(activity, "illegal requestCode:" + requestCode, Toast.LENGTH_SHORT).show();
            return;
        }

        Log.i(TAG, "onRequestPermissionsResult requestCode:" + requestCode + ",permissions:" + permissions.toString()
                + ",grantResults:" + grantResults.toString() + ",length:" + grantResults.length);

        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.i(TAG, "onRequestPermissionsResult PERMISSION_GRANTED");
            //TODO success, do something, can use callback
            if (permissionGrant!=null){
                permissionGrant.onPermissionGranted(requestCode, "onRequestPermissionsResult PERMISSION_GRANTED");
            }
        } else {
            //TODO hint user this permission function
            Log.i(TAG, "onRequestPermissionsResult PERMISSION NOT GRANTED");

            String requestPermission = requestPermissions[requestCode];
            if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
                Log.i(TAG, "requestPermission shouldShowRequestPermissionRationale");
                shouldShowRationale(activity, requestCode, requestPermission, permissionGrant);
            } else {
                Log.i(TAG, "requestPermission from system set page");
                String[] permissionsHint = activity.getResources().getStringArray(R.array.permissions);
                String permissionsSetPath = activity.getResources().getString(R.string.permission_set_path_hint);
                openSettingActivity(activity, requestCode, requestPermission, permissionGrant, permissionsHint[requestCode] + "\n" + permissionsSetPath);
            }
        }
    }

    public static void openSettingActivity(final Activity activity, final int requestCode, final String requestPermission, final PermissionGrant permissionGrant, String message) {
        showMessageOKCancel(activity, message, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Log.d(TAG, "getPackageName(): " + activity.getPackageName());
                Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                intent.setData(uri);
                activity.startActivityForResult(intent, requestCode);
            }
        }, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.d(TAG, "showMessage cancel requestPermissions:" + requestPermission);
                if(permissionGrant!=null){
                    String requestStr="";
                    if(requestCode == CODE_MULTI_PERMISSION){
                        requestStr = "part permission";
                    }else{
                        requestStr = requestPermissions[requestCode];
                    }
                    permissionGrant.onPermissionDeny(requestCode,"denyed:" + requestStr);
                }
            }
        });
    }

    /**
     * @param activity
     * @return
     */
    public static ArrayList<String> getNoGrantedPermission(Activity activity, int[] requestCodeList) {
        ArrayList<String> permissions = new ArrayList<>();

        if(requestCodeList==null || requestCodeList.length==0){
            return null;
        }

        String[] curRequestPermissionList = new String[requestCodeList.length];
        for (int i = 0; i < requestCodeList.length; i++) {
            int requestCodeValue = requestCodeList[i];

            Log.i(TAG, "requestPermission requestCode:" + requestCodeValue);
            if (requestCodeValue < 0 || requestCodeValue >= requestPermissions.length) {
                Log.w(TAG, "requestPermission illegal requestCode:" + requestCodeValue);
                return null;
            }
            curRequestPermissionList[i] = requestPermissions[requestCodeValue];
        }

        for (int i = 0; i < curRequestPermissionList.length; i++) {
            String requestPermission = curRequestPermissionList[i];

            //TODO checkSelfPermission
            int checkSelfPermission = -1;
            try {
                checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
            } catch (RuntimeException e) {
                Toast.makeText(activity, "please open those permission", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "RuntimeException:" + e.getMessage());
                return null;
            }

            if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "getNoGrantedPermission ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED:" + requestPermission);

                permissions.add(requestPermission);
                Log.i(TAG, "add permission:" + requestPermission);
            }
        }

        return permissions;
    }

    /**
     * @param activity
     * @return
     */
    public static ArrayList<String> getNoGrantedPermissionShowRationale(Activity activity, String[] permissionList) {
        ArrayList<String> permissions = new ArrayList<>();

        for (int i = 0; i < permissionList.length; i++) {
            String requestPermission = permissionList[i];

            //TODO checkSelfPermission
            int checkSelfPermission = -1;
            try {
                checkSelfPermission = ActivityCompat.checkSelfPermission(activity, requestPermission);
            } catch (RuntimeException e) {
                Toast.makeText(activity, "please open those permission", Toast.LENGTH_SHORT).show();
                Log.e(TAG, "RuntimeException:" + e.getMessage());
                return null;
            }

            if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
                Log.i(TAG, "getNoGrantedPermission ActivityCompat.checkSelfPermission != PackageManager.PERMISSION_GRANTED:" + requestPermission);
                if (ActivityCompat.shouldShowRequestPermissionRationale(activity, requestPermission)) {
                    Log.d(TAG, "shouldShowRequestPermissionRationale if");

                    permissions.add(requestPermission);
                }
            }
        }

        return permissions;
    }

    /**
     * 判断某一个权限是否已授权
     * @param context
     * @return
     */
    public static boolean getAppOps(Context context, String opStr, int op) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkResult = -1;
            AppOpsManager appOpsManager = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
            try {
                checkResult = appOpsManager.checkOpNoThrow(opStr, Binder.getCallingUid(), context.getPackageName());
            } catch (Exception e) {
            }

            if (checkResult == AppOpsManager.MODE_ALLOWED) {
                return true;
            } else if (checkResult == AppOpsManager.MODE_IGNORED) {
                // "被禁止了"
                return false;
            } else if (checkResult == AppOpsManager.MODE_ERRORED) {
                // "出错了"
                return false;
            } else if (checkResult == 4) {
                // "权限需要询问"
                return false;
            }else {
                return true;
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            try {
                Object object = context.getSystemService(Context.APP_OPS_SERVICE);
                if (object == null) {
                    return false;
                }
                Class localClass = object.getClass();
                Class[] arrayOfClass = new Class[3];
                arrayOfClass[0] = Integer.TYPE;
                arrayOfClass[1] = Integer.TYPE;
                arrayOfClass[2] = String.class;
                Method method = localClass.getMethod("checkOp", arrayOfClass);
                if (method == null) {
                    return false;
                }
                Object[] arrayOfObject1 = new Object[3];
                arrayOfObject1[0] = op;
                arrayOfObject1[1] = Integer.valueOf(Binder.getCallingUid());
                arrayOfObject1[2] = context.getPackageName();
                int m = ((Integer) method.invoke(object, arrayOfObject1)).intValue();
                return m == AppOpsManager.MODE_ALLOWED;
            } catch (Exception ex) {
            }
        }

        return true;
    }

    public static final int CODE_OVERLAY = 8;

    /**
     * 是否已授权弹出框权限
     * @param context
     * @param defaultValue 不考虑sdk19以下的权限，给个默认值
     * @return
     */
    public static boolean isGrantedSystemAlert(Context context, boolean defaultValue) {
        if (context == null) {
            return false;
        }
        if (Build.VERSION.SDK_INT >= 23) {
            return Settings.canDrawOverlays(context);
        }else if(Build.VERSION.SDK_INT >= 19){
            // OP_SYSTEM_ALERT_WINDOW = 24
            return getAppOps(context, AppOpsManager.OPSTR_SYSTEM_ALERT_WINDOW, 24);
        } else {
            return defaultValue;
        }
    }

    /**
     * 打开弹出框的权限
     * @param fragment
     * @return
     */
    public static void openGrantedSystemAlert(final Fragment fragment, final int requestCode, DialogInterface.OnClickListener cancelClickListener) {
        if (fragment == null) {
            return;
        }
        new AlertDialog.Builder(fragment.getContext())
                .setCancelable(false)
                .setMessage("该手机需要手动开启悬浮窗权限,请在\"设置\"-\"应用管理\"-\"好得财富\"的页面中设置!")
                .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (Build.VERSION.SDK_INT >= 23) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + fragment.getContext().getPackageName()));
                            fragment.startActivityForResult(intent, requestCode);
                        }else{
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Log.d(TAG, "getPackageName(): " + fragment.getContext().getPackageName());
                            Uri uri = Uri.fromParts("package", fragment.getContext().getPackageName(), null);
                            intent.setData(uri);
                            fragment.startActivityForResult(intent, requestCode);
                        }
                    }
                })
                .setNegativeButton("暂不", cancelClickListener)
                .create()
                .show();
    }
}
